import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:water_mark/message.dart';
import 'package:water_mark/pigeon.dart';
import 'package:water_mark/water_mark.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:water_mark/water_mark_file_path.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  Uint8List? memonyfile;
  String? filePath;
  // HostBookApi? hostApi;
  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    BookApi api = BookApi();
    var cc=  await api.search("??????");
    cc.forEach((element) { print("title:${element?.title},auth:${element?.author},${DateTime.now().millisecondsSinceEpoch}");});
    // String platformVersion;
    // // Platform messages may fail, so we use a try/catch PlatformException.
    // try {
    //   platformVersion = await WaterMark.platformVersion;
    //   var list = await WaterMark.listbook;
    //   list.forEach((element) {
    //     print("${element}");
    //   });
    // } on PlatformException {
    //   platformVersion = 'Failed to get platform version.';
    // }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    Response rs;
    rs = await Dio().get<ResponseBody>("http://120.211.112.89:12321/api/event//202109/875c536c-7ce7-4038-8315-a2c6324b0e2f202109.jpg",
      options: Options(responseType: ResponseType.stream),  //设置接收类型为stream
    );
    // Dio().download(urlPath, savePath)
    ResponseBody resp = rs.data;
    // final Uint8List bytes = await consolidateHttpClientResponseBytes(resp);
    // print(rs?.data?.stream);
    Directory appDocDir = (await getExternalStorageDirectory())!;
    String appDocPath = appDocDir.path;
    var data = await consolidateHttpClientResponseBytes(resp);
    var startTime=DateTime.now().millisecondsSinceEpoch;
    var path = "$appDocPath/${DateTime.now()}.jpg";
    var file = File(path);
    await file.writeAsBytes(data);
    var afff =await WaterMarkFilePathApi().fileToWaterMark(WaterMarkFilePathRequest()..backgroundfilePath=path..textContext="时间：2021-10-29 09:09:19\n地点：唐山\n人员：asd"..fontSize=130);

    //  var afff =await WaterMarkApi().fileToWaterMark(WaterMarkFileRequest()..textContext="时间：2021-10-29 09:09:09\n地点：唐山\n人员：asd"..fontSize=130..backgroundfile=data);
    //  memonyfile =afff.waterMarkfile;

    print("用时：${DateTime.now().millisecondsSinceEpoch-startTime}");

    // WaterMarkApi().fileToWaterMark(arg_request)
    setState(() {
    filePath = afff.waterMarkfilePath;
      // _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Image.file(File(filePath??"")),
        ),
      ),
    );
  }

  Future<Uint8List> consolidateHttpClientResponseBytes(
      ResponseBody response) {
    // response.contentLength is not trustworthy when GZIP is involved
    // or other cases where an intermediate transformer has been applied
    // to the stream.
    final Completer<Uint8List> completer = Completer<Uint8List>.sync();
    final List<List<int>> chunks = <List<int>>[];
    int contentLength = 0;
    response.stream.listen((List<int> chunk) {
      chunks.add(chunk);
      contentLength += chunk.length;
    }, onDone: () {
      final Uint8List bytes = Uint8List(contentLength);
      int offset = 0;
      for (List<int> chunk in chunks) {
        bytes.setRange(offset, offset + chunk.length, chunk);
        offset += chunk.length;
      }
      completer.complete(bytes);
    }, onError: completer.completeError, cancelOnError: true);

    return completer.future;
  }

}
